<?php

namespace App\Models\Admin\Framework;

use App\Master\Framework\Extend\DataUtil;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AdminGroupModel extends Model
{
    use HasFactory;

    protected $table = 'admin_group';
    public $timestamps = false;

    /**
     * 列表页
     * @return array
     */
    public static function getGroupPage(){
        $menus = self::query()->whereIn('status', [1, 2])->where('is_delete', 0)
            ->select(['id','parent_id','name','status','level','description','created_at','updated_at'])
            ->orderBy('id', 'asc')->get()->toArray();
        if(empty($menus)){
            return [
                'rows'  => [],
                'total' => 0
            ];
        }
        return [
            'rows'  => DataUtil::recursion($menus, 'id', 'parent_id'),
            'total' => self::query()->whereIn('status', [1, 2])->where('is_delete', 0)->count()
        ];
    }

    /**
     * 获取组织树形结构
     * @param int $level 组织级别
     * @return array
     */
    public static function getGroupParentsTree(int $level = 2)
    {
        $groups = self::query()->select(['id as value', 'name as label', 'parent_id'])
            ->where(['status' => 1, 'is_delete' => 0])
            ->where('level', '<=', $level)
            ->orderBy('id', 'desc')->get()->toArray();
        if (empty($groups)) {
            return [];
        }
        return DataUtil::recursion($groups, 'value', 'parent_id');
    }
}
